#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <poll.h>
#include "log.hpp"
#include "Socket.hpp"

using namespace LogModule;
using namespace SocketModule;

//#define NUM sizeof(fd_set)*8
#define MAX 4096
const int gdefaultfd = -1;

class PollServer
{
public:
    PollServer(uint16_t port)
    :_port(port)
    ,_listen_socket(std::make_unique<TcpSocket>())
    ,_is_running(false)
    {}
    void Init()
    {
        _listen_socket->BuildTcpSocketMethod(_port);
        for(int i = 0;i<MAX;++i)
        {
            _fds[i].fd = gdefaultfd;
            _fds[i].events = 0;
            _fds[i].revents = 0;
        }
        _fds[0].fd = _listen_socket->Fd();
        _fds[0].events |= POLLIN;
    }
    void loop()
    {
        fd_set rfds;//读文件描述符集
        _is_running = true;
        while(_is_running)
        {
            int n = poll(_fds,MAX,-1);
            switch (n)
            {
            case 0:
                std::cout<<"time out..."<<std::endl;
                break;
            case -1:
                perror("select");
                break;
            default:
                //事件就绪
                //std::cout<<"事件就绪,timeout: "<<timeout.tv_sec<<":"<<timeout.tv_usec<<std::endl;
                Dispatcher();
                break;
            }
        }
    }
    //分发任务
    void Dispatcher()
    {
        for(int i = 0;i<MAX;++i)
        {
            if(_fds[i].fd == gdefaultfd)
                continue;
            if(_fds[i].fd == _listen_socket->Fd())
            {
                if(_fds[i].revents & POLLIN)
                    Accepter();//获取链接
            }
            else
            {
                if(_fds[i].revents & POLLIN)
                    Recver(i);//处理IO
            }
        }
        
    }
    //accept新连接
    void Accepter()
    {
        InetAddr client;
        SockPtr sockp = _listen_socket->Accept(&client);
        //搜索表中空闲位置
        int pos = -1;
        for(int i = 0;i<MAX;++i)
        {
            if(_fds[i].fd == gdefaultfd)
            {
                pos = i;
                break;
            }
        }
        if(pos == -1)
        {
            std::cout<<"服务器繁忙..."<<std::endl;
            sockp->Close();
        }
        else
        {
            _fds[pos].fd = sockp->Fd();
            _fds[pos].events |= POLLIN;
            std::cout<<"新连接建立,ip:"<<client.Ip()<<" fd:"<<_fds[pos].fd<<std::endl; 
        }
    }
    void Recver(int who)
    {
        char buffer[1024] = {0};
        int n = recv(_fds[who].fd,buffer,sizeof(buffer)-1,0);//因为文件描述符就绪，所以不会阻塞
        if(n>0)
        {
            std::cout<<"收到消息"<<buffer<<std::endl;
            //读到内容，回传给客户端
            std::string echo("server echo:");
            echo += buffer;
            send(_fds[who].fd,echo.c_str(),echo.size(),0);
        }
        else if(n == 0)
        {
            std::cout<<"client quit,sockfd:"<<_fds[who].fd<<std::endl;
            close(_fds[who].fd);
            //删除对应的表中内容
            _fds[who].fd = gdefaultfd;
            _fds[who].events = 0;
            _fds[who].revents = 0;
        }
        else
        {
            std::cout<<"recv error,disconnect:"<<_fds[who].fd<<std::endl;
            close(_fds[who].fd);
            _fds[who].fd = gdefaultfd;
            _fds[who].events = _fds[who].revents = 0;
        }
    }
private:
    uint16_t _port;//端口号
    std::unique_ptr<Socket> _listen_socket;//监听套接字
    bool _is_running;
    struct pollfd _fds[MAX]; 
};
